package io.adminboot.service.impl;

import io.adminboot.domain.vo.PageVO;
import io.adminboot.entity.ScheduleJob;
import io.adminboot.entity.ScheduleJobLog;
import io.adminboot.repository.extend.ScheduleJobExtMapper;
import io.adminboot.service.ScheduleJobService;
import io.adminboot.utils.Constant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service("scheduleJobService")
public class ScheduleJobServiceImpl implements ScheduleJobService {
    @Autowired
    private ScheduleJobExtMapper mapper;

    @Override
    public PageVO queryPage(String beanName, int pageNum, int pageSize) {
        List<ScheduleJobLog> list = mapper.selectList(beanName, (pageNum - 1) * pageSize, pageSize);
        int totalCount = mapper.count(beanName);
        PageVO page = new PageVO(list, totalCount, pageSize, pageNum);
        return page;

    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(ScheduleJob scheduleJob) {
        scheduleJob.setCreateTime(new Date());
        scheduleJob.setStatus(Constant.ScheduleStatus.NORMAL.getValue());
        mapper.insert(scheduleJob);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(ScheduleJob scheduleJob) {
        mapper.updateByPrimaryKey(scheduleJob);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(Long[] jobIds) {
        for (Long jobId : jobIds) {

        }

        //删除数据
        mapper.batchDeleteByIds(Arrays.asList(jobIds));
    }

    @Override
    public int updateBatch(Long[] jobIds, int status) {
        return mapper.batchUpdateStatus(jobIds, status);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void run(Long[] jobIds) {
        for (Long jobId : jobIds) {
            ScheduleJob scheduleJob = mapper.selectByPrimaryKey(jobId);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void pause(Long[] jobIds) {
        for (Long jobId : jobIds) {
        }

        updateBatch(jobIds, Constant.ScheduleStatus.PAUSE.getValue());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void resume(Long[] jobIds) {
        for (Long jobId : jobIds) {
        }

        updateBatch(jobIds, Constant.ScheduleStatus.NORMAL.getValue());
    }

    @Override
    public ScheduleJob selectById(Long jobId) {
        return mapper.selectByPrimaryKey(jobId);
    }

}
